package cn.etg.day05;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Scanner;

/**
 * 要求用户输入若干员工信息，格式为：
 * name,age,gender,salary,hiredate;name,age,gender,salary,hiredate;....
 * 例如:
 * 张三,25,男,5000,2006-02-15;李四,26,女,6000,2007-12-24;...
 * 然后将每个员工信息解析成Emp对象。并存入到一个List集合中。
 * 并对集合排序，然后输出每个员工信息。
 *
 * 再根据员工的入职时间排序，入职晚的在前，早的在后并
 * 输出每个员工的信息。
 * @author Xiloer
 *
 */

public class Test03 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入员工信息（格式：name,age,gender,salary,hiredate;...）：");
        String input = scanner.nextLine();
        scanner.close();

        List<Emp> employees = parseEmployeeData(input);

        // 按年龄排序
        Collections.sort(employees);
        System.out.println("按年龄排序后的员工信息：");
        for (Emp emp : employees) {
            System.out.println(emp);
        }

        // 按入职时间排序
        Collections.sort(employees, new Comparator<Emp>() {
            @Override
            public int compare(Emp emp1, Emp emp2) {
                return emp2.getHiredate().compareTo(emp1.getHiredate());
            }
        });
        System.out.println("按入职时间排序后的员工信息：");
        for (Emp emp : employees) {
            System.out.println(emp);
        }
    }

    private static List<Emp> parseEmployeeData(String data) {
        List<Emp> employees = new ArrayList<>();
        String[] employeeStrings = data.split(";");

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        for (String employeeString : employeeStrings) {
            String[] fields = employeeString.split(",");
            if (fields.length == 5) {
                try {
                    String name = fields[0];
                    int age = Integer.parseInt(fields[1]);
                    String gender = fields[2];
                    int salary = Integer.parseInt(fields[3]);
                    Date hiredate = sdf.parse(fields[4]);

                    Emp emp = new Emp(name, age, gender, salary, hiredate);
                    employees.add(emp);
                } catch (NumberFormatException | ParseException e) {
                    System.out.println("解析员工信息出错：" + employeeString);
                }
            }
        }

        return employees;
    }
}